import store from "@/store";
import axios from "axios";
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "home",
    component: () => import("../views/HomeIndex.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/LoginIndex.vue"),
    meta: { redirectAlredyLogin: true },
  },
  {
    path: "/signup",
    name: "signup",
    component: () => import("../views/SignUp.vue"),
    // meat:
  },
  {
    path: "/column/:id",
    name: "column",
    component: () => import("../views/ColumnDetail.vue"),
    meta: { requiredLogin: true },
  },
  {
    path: "/create",
    name: "create",
    component: () => import("../components/CreatePost.vue"),
    meta: { requiredLogin: true },
  },
  {
    path:'/posts/:id',
    name:'post',
    component:()=>import('../views/PostsDetail.vue'),
    meta: { requiredLogin: true },
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// to ：要进入的目标
// from：要离开的目标
// next()：如果有 next() 方法跳转 指向下一个路由
// router.beforeEach((to,from,next)=>{
//     if(to.name !=='login' && !store.state.user.isLogin) {
//         next({name:'login'})
//     }else {
//         next()
//     }
// })

// 通过路由原信息

// router.beforeEach((to, from, next) => {
//   console.log(to.meta);
//   if (to.meta.requiredLogin && !store.state.user.isLogin) {
//     next({ name: "login" });
//   } else if (to.meta.redirectAlredyLogin && store.state.user.isLogin) {
//     next("/");
//   } else {
//     next();
//   }
// });

router.beforeEach((to, form, next) => {
  const { user, token } = store.state;
  const { redirectAlredyLogin, requiredLogin } = to.meta;
  if (!user.isLogin) {
    // 没有登录
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      store.dispatch("fetchCurrentUser")
        .then(() => {
          // 判断有没有进入登录页面
          if (redirectAlredyLogin) {
            next("/");
          } else {
            next();
          }
        })
        // e  失败回调的返回值
        .catch((e) => {
          console.log(e);
          store.commit('logout')
          next("/login");
        });
    } else {
      if (requiredLogin) {
        next("/login");
      } else {
        next();
      }
    }
  } else {
    //登录
    if (redirectAlredyLogin) {
      next("/");
    } else {
      next();
    }
  }
});
export default router;
